package com.mifengs.mall.ui.my;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.hyphenate.chat.ChatClient;
import com.hyphenate.helpdesk.callback.Callback;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.R;
import com.mifengs.mall.adapter.RedPacketAdapter;
import com.mifengs.commonbase.base.BaseFragment;
import com.mifengs.mall.di.component.DaggerRedPacketComponent;
import com.mifengs.mall.di.module.RedPacketModule;
import com.mifengs.mall.entity.RedPacket;
import com.mifengs.mall.event.MainEvent;
import com.mifengs.mall.event.RedPacketEvent;
import com.mifengs.mall.ui.login.LoginActivity;
import com.mifengs.mall.widget.BlankPageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class RedPacketFragment extends BaseFragment<RedPacketPresent> implements RedPacketContract.View ,SwipeRefreshLayout.OnRefreshListener,BaseQuickAdapter.RequestLoadMoreListener{


    @BindView(R.id.rv_list)
    RecyclerView mRvList;
    @BindView(R.id.swipe_container)
    SwipeRefreshLayout mSwipeContainer;

    private RedPacketAdapter mRedPacketAdapter;
    private int mCurrentPage;
    private int mType;

    public RedPacketFragment() {
    }


    public static RedPacketFragment newInstance(int type) {
        RedPacketFragment fragment = new RedPacketFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            mType = getArguments().getInt("type");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_red_packet, container, false);
        ButterKnife.bind(this, view);
        init();
        return view;
    }

    @Override
    public void initInjector() {
        DaggerRedPacketComponent.builder()
                .redPacketModule(new RedPacketModule(this))
                .build()
                .inject(this);
    }

    private void init() {
        mCurrentPage = 1;
        mSwipeContainer.setOnRefreshListener(this);
        mSwipeContainer.setRefreshing(true);
        mRedPacketAdapter = new RedPacketAdapter(null,getContext(),mType);
        mRedPacketAdapter.setOnLoadMoreListener(this,mRvList);
        mRedPacketAdapter.openLoadAnimation();
        BlankPageView blankPageView = new BlankPageView(getContext());
        blankPageView.initViewData(BlankPageView.no_red_packet);
        mRedPacketAdapter.setEmptyView(blankPageView);
        mRvList.setLayoutManager(new LinearLayoutManager(getContext()));
        mRvList.setAdapter(mRedPacketAdapter);
        mRvList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(getActivity(), RedPacketDetailActivity.class);
                List<RedPacket> redPacketList = adapter.getData();
                RedPacket redPacket = redPacketList.get(position);
                TextView needTimeTextView = view.findViewById(R.id.tv_status_time);
                TextView tvRevStatusTextView = view.findViewById(R.id.tv_rev_status);
                String needTime = "";
                String reStatus = "";
                if(needTimeTextView!=null){
                    needTime =  needTimeTextView.getText().toString();
                }
                if(tvRevStatusTextView !=null){
                    reStatus = tvRevStatusTextView.getText().toString();
                }
                intent.putExtra("redPacket",redPacket);
                intent.putExtra("needTime",needTime);
                intent.putExtra("reStatus",reStatus);
                startActivity(intent);
            }
        });
        if(mType==0){
            mRedPacketAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {

                    List<RedPacket> redPacketList = adapter.getData();
                    RedPacket redPacket = redPacketList.get(position);
                    if(redPacket.getReceiveStatus()==0){
                        mPresenter.revRedPacketData(redPacket);
                    }
                }
            });
        }
        mPresenter.getRedPacketData(1,mType);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onRefresh() {
        mCurrentPage=1;
        mPresenter.getRedPacketData(mCurrentPage,mType);
    }

    @Override
    public void setData(final List<RedPacket> data,boolean isLoadOver) {
        if(isLoadOver){
            mRvList.post(new Runnable() {
                @Override
                public void run() {
                    mRedPacketAdapter.setNewData(data);
                    mRedPacketAdapter.loadMoreEnd(true);
                }
            });
        }else{
            mRedPacketAdapter.setNewData(data);
        }

    }

    @Override
    public void setRefreshState(boolean state) {
        if(mSwipeContainer!=null){
            mSwipeContainer.setRefreshing(state);
        }
    }

    @Override
    public void setMoreData(final List<RedPacket> list, final boolean isLoadOver) {
        mRvList.post(new Runnable() {
            @Override
            public void run() {
                mRedPacketAdapter.addData(list);
                if(isLoadOver){
                    mRedPacketAdapter.loadMoreEnd(true);
                }else{
                    loadMoreComplete();
                }
            }
        });
    }

    @Override
    public void loadMoreFail() {
        mRedPacketAdapter.loadMoreFail();
    }

    @Override
    public void loadMoreComplete() {
        mRedPacketAdapter.loadMoreComplete();
    }

    @Override
    public void loadMoreEnd() {
        mRedPacketAdapter.loadMoreEnd();
    }

    @Override
    public void refreshData() {
        mSwipeContainer.setRefreshing(true);
        mCurrentPage=1;
        mPresenter.getRedPacketData(mCurrentPage,mType);
    }

    @Override
    public void goToLogin() {
        logout();
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    private void logout() {
        PreferenceUtils.clearLoginInfo();
        CookieSyncManager.createInstance(getContext());
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
        EventBus.getDefault().post(new MainEvent(MainEvent.TOHOMEPAGE));
        try {
            if (ChatClient.getInstance().isLoggedInBefore()) {
                ChatClient.getInstance().logout(true, new Callback() {
                    @Override
                    public void onSuccess() {

                    }

                    @Override
                    public void onError(int i, String s) {

                    }

                    @Override
                    public void onProgress(int i, String s) {

                    }
                });
            }
        }catch (Exception e){
            Log.e("ChatClient",e.toString());
        }
    }

    @Override
    public void onLoadMoreRequested() {
        setRefreshState(false);
        mCurrentPage++;
        mPresenter.getRedPacketData(mCurrentPage,mType);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RedPacketEvent event) {
        switch (event.action) {
            case RedPacketEvent.REFRESH:
                refreshData();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
